<template>
  <div>
    <list-page
      ref="listPage"
      :stripe='true'
      :columns='tableColumns'
      :columnKey='columnKey'
      :data='listData'
      :loading='loading'
      :totalCount='totalCount'
      :pageIndex='pageIndex'
      @load-data='loadData'
      @show-add='showAddModel'
      @show-edit='showEditModel'
      @delete-handle='deleteActionHandle'>
    </list-page>

    <Modal
        :title="modalTitle"
        v-model="modalShow"
        :mask-closable="false"
        :closable="false"
        :footer-hide="true"
        scrollable
        class-name="vertical-center-modal">
      <Form :ref="formRef" :model="formData" label-position="right" :rules="formValidateRule" :label-width="100">
        <input v-model="formData.clientId" name="clientId" type="hidden">
        <FormItem label="应用名称" prop="clientName">
            <Input v-model="formData.clientName" name="clientName" placeholder="应用名称"></Input>
        </FormItem>
        <FormItem label="clientSecret" prop="clientSecret">
            <Input v-model="formData.clientSecret" name="clientSecret" placeholder="clientSecret"></Input>
        </FormItem>
        <FormItem label="应用首页" prop="webHomeUrl">
            <Input v-model="formData.webHomeUrl" name="webHomeUrl" placeholder="应用首页"></Input>
        </FormItem>
        <FormItem label="应用类型">
            <RadioGroup v-model="formData.clientType">
              <Radio label="2">第三方应用</Radio>
              <Radio label="1">子应用</Radio>
              <Radio label="0">系统应用</Radio>
            </RadioGroup>
        </FormItem>
        <FormItem label="可信应用">
            <RadioGroup v-model="formData.autoApprove">
              <Radio label="true">是</Radio>
              <Radio label="false">否</Radio>
            </RadioGroup>
        </FormItem>
        <FormItem label="授权模式">
            <CheckboxGroup v-model="formData.authorizedGrantTypes">
                <Checkbox label="authorization_code"></Checkbox>
                <Checkbox label="implicit"></Checkbox>
                <Checkbox label="password"></Checkbox>
                <Checkbox label="refresh_token"></Checkbox>
            </CheckboxGroup>
        </FormItem>
        <FormItem>
           <div style="float: right;">
             <Button style="margin-right: 10px" @click="formCancelHandle">取消</Button>
            <Button type="primary" @click="formSaveHandle">保存</Button>
           </div>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
import ListPage from '@/components/list-page'
import { mapActions } from 'vuex'
export default {
  name: 'clientManage',
  components: {
    ListPage
  },
  data () {
    return {
      tableColumns: [
        {
          type: 'index',
          title: '序号',
          align: 'center',
          width: 60
        },
        {
          title: '应用编号',
          key: 'clientId'
        },
        {
          title: '应用名称',
          key: 'clientName'
        },
        {
          title: '首页',
          key: 'webHomeUrl'
        },
        {
          title: '更新时间',
          key: 'updateTime'
        }
      ],
      columnKey: 'clientId',
      listData: [],
      loading: false,
      totalCount: 100,
      pageIndex: 1,
      modalTitle: 'title',
      modalShow: false,
      formRef: 'editForm',
      formData: {},
      formValidateRule: {}
    }
  },
  methods: {
    ...mapActions('clientStore', [
      'getValidateRule', 'loadList', 'save', 'delete'
    ]),
    loadData: function (pageInfo) {
      console.log('>> load-data')
      if (!pageInfo) {
        pageInfo = {
          pageIndex: this.pageIndex,
          pageSize: this.pageSize
        }
      }
      // console.log('>>>pageInfo', pageInfo)
      this.loading = true
      this.loadList(pageInfo)
        .then(res => {
          this.totalCount = res.data.total
          let data = res.data.list.map((item, index) => {
            let itemMap = this.$contextUtils.convertObjectNumberPropertieToString(item)
            return itemMap
          })
          this.listData = data
          this.loading = false
        })
        .catch(err => {
          console.log(err)
          this.loading = false
        })
    },
    clearFormData: function () {
      this.$refs[this.formRef].resetFields()
      this.formData = {}
    },
    showAddModel () {
      this.clearFormData()
      this.formData = {
        clientType: '1',
        authorizedGrantTypes: [ 'authorization_code', 'implicit' ],
        autoApprove: 'false',
        webHomeUrl: 'http://'
      }
      console.log('showAdd')
      this.modalTitle = '新增'
      this.modalShow = true
    },
    showEditModel (params) {
      this.clearFormData()
      this.modalTitle = '编辑'
      this.modalShow = true
      for (let prop in params.row) {
        this.formData[prop] = params.row[prop]
      }
      let grantTypes = this.formData.authorizedGrantTypes.split(',')
      this.formData.authorizedGrantTypes = grantTypes
    },
    deleteActionHandle (params) {
      console.log(params.row.clientId)
      this.delete({
        clientId: params.row.clientId
      }).then(res => {
        // console.log(res)
        this.$Message.info('删除成功')
        this.loadData()
      }).catch(err => {
        this.$Message.error(err)
      })
    },
    formCancelHandle () {
      this.modalShow = false
    },
    formSaveHandle () {
      console.log(' >>> save ')
      let grantTypes = ''
      let grantLenth = this.formData.authorizedGrantTypes.length
      for (var i = 0; i < grantLenth; i++) {
        grantTypes += this.formData.authorizedGrantTypes[i]
        if (i < grantLenth - 1) {
          grantTypes += ','
        }
      }
      const requestData = {
        clientId: this.formData.clientId,
        clientName: this.formData.clientName,
        clientSecret: this.formData.clientSecret,
        webHomeUrl: this.formData.webHomeUrl,
        clientType: this.formData.clientType,
        autoApprove: this.formData.autoApprove,
        authorizedGrantTypes: grantTypes
      }
      console.log(requestData)
      this.$refs[this.formRef].validate((valid) => {
        if (!valid) {
          this.$Message.error('输入信息不合法')
        } else {
          // requestData.authorizedGrantTypes = grantTypes

          this.save(requestData).then(res => {
            this.clearFormData()
            this.modalShow = false
            this.$Message.info('保存成功')
            this.loadData()
          }).catch(err => {
            this.$Message.info(err)
          })
        }
      })
    }
  },
  created () {
    // 加载验证规则
    this.getValidateRule().then(val => {
      this.formValidateRule = {}
      for (let ruleColumn in val) {
        this.formValidateRule[ruleColumn] = val[ruleColumn]
      }
    })
  }
}
</script>

<style>

</style>
